package com.toocms.jinjuhang.widget.view_model

import androidx.fragment.app.DialogFragment
import com.blankj.utilcode.util.ToastUtils
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.ui.login.LoginFgt
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.network.ApiTool
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

fun BaseViewModel<*>.checkLoginStatus(): Boolean {
    if (!UserRepository.isLogin()) {
        startFragment(LoginFgt::class.java)
    }
    return UserRepository.isLogin()
}


fun <T> BaseViewModel<*>.requestData(
    url: String,
    params: Map<String, String?> = mapOf(),
    filePaths: Map<String, String?> = mapOf(),
    resultClass: Class<T>,
    isShowLoading: Boolean = false,
    result: (data: T) -> Unit,
    error: ((Throwable) -> Unit)? = null,
    finish: (() -> Unit)? = null
) {
    ApiTool.post(url).run {
        params.entries.forEach {
            add(it.key, it.value)
        }
        filePaths.entries.forEach {
            addFile(it.key, it.value)
        }
        if(filePaths.entries.isNotEmpty()) asUpload {

        }
        asTooCMSResponse(resultClass).run {
            onFinally(finish)
            withViewModel(this@requestData)
        }
    }.apply {
        showLoading(isShowLoading)
        if (null != error) {
            request(result, error)
        } else {
            request(result)
        }
    }
}

fun <T> DialogFragment.requestData(
    url: String,
    params: Map<String, String?> = mapOf(),
    resultClass: Class<T>,
    result: (data: T) -> Unit,
    error: ((Throwable) -> Unit)? = null,
    finish: (() -> Unit)? = null
) {
    ApiTool.post(url).apply {
        params.entries.forEach {
            add(it.key, it.value)
        }
    }.asTooCMSResponse(resultClass).apply {
        onFinally(finish)
        observeOn(AndroidSchedulers.mainThread())
        if (null != error) {
            request(result, error)
        } else {
            request(result)
        }
    }
}

fun DialogFragment.showToast(content: CharSequence) {
    ToastUtils.showShort(content)
}
